#!/usr/bin/env python
import os, sys
from simpledcpp.core.base import DCPPPart
class FileListGenerator(DCPPPart):
	file = None
	filelist = None
	try_use_tth = False
	def __init__(self, parent, filelist = None):
                DCPPPart.__init__(self, parent)
                self.__temp = '/tmp'
                if os.getenv('TEMP') != None:
			if os.path.isdir(os.getenv('TEMP')):
	                        self.__temp = os.getenv('TEMP')

		self.filelist = filelist
		self.dirstack = list()
		if filelist == None:
			self.try_use_tth = False	
		else:
			self._ufilelist = {}
			for i in self.filelist:
				self._ufilelist[i.encode('utf-8')] = self.filelist[i]
			self.try_use_tth = True

	def Regenerate(self, dirlist, filename):
		self.Generate(dirlist, filename)

	def _getcount(self, dir):
		os.system('find "%s" -type f | wc -l > %s/countfiles'%(dir,self.__temp))
		try:
			count = int(open('%s/countfiles'%self.__temp).readlines()[0].strip())
		except:
			return 0
			print sys.exc_info()
		os.remove('%s/countfiles'%self.__temp)
		return count

	def Generate(self,dirlist, filename):
		print "Prepare.."
		self._countfiles = 0
		self._alreadyfiles = 0
		for i in dirlist:
			self._countfiles = self._countfiles + self._getcount(i[1])
		print "Files: %s"%self._countfiles
		try:
			os.remove(filename + '.bz2')
		except:
			pass
		self.file = open(filename, 'w')
		self._generateHeaders()
			
		for i in dirlist:
			self.print_current("",i[1], i[1], i[0])
		self._generateFinish()
		self.file.close()
		os.system('bzip2 "%s"'%filename)

	def _print(self, string, step = 0):
		try:
			for i in range(0,step):
				self.file.write(' ')
			try:
				string = string.encode('utf-8')
			except:
				pass
			self.file.write(string+'\n')
		except:
			print sys.exc_info()

	def _generateDirectory(self, directoryname, step = 0):
		self.dirstack.append(directoryname)
		self._print('<Directory Name="%s">'%(directoryname.replace("&","&amp;")), step)

	def _getHash(self, filename):
		strd = '/'
		for i in self.dirstack:
			if i!="":
				strd = strd + i + '/'
		filen = filename.split('/')
		filen = filen[-1]
		print "%s"%(strd + filen),	
		if self.try_use_tth:	
			try:
				if self._ufilelist.has_key((strd  + filen).encode('utf-8')):
					print "OK",
					return self._ufilelist[(strd + filen).encode('utf-8')][1]	
			except:
				print sys.exc_info()

		try:
			tmp = None
			try:
				os.system('tthsum "%s" > %s/tthsum.tmp 2>/dev/null'%(filename,self.__temp))
			except:
				print "Here"
			hashf = open('%s/tthsum.tmp'%self.__temp)
			hashl = hashf.readlines()
			if hashl != []:
				hashl = hashl[0].strip()
				tmp = hashl.split('  ')
				tmp = tmp[0]
			hashf.close()
			print (strd+filen).encode('utf-8')
			os.remove('%s/tthsum.tmp'%self.__temp)
			print "REHASHED",
			return tmp
		except:
#			print sys.exc_info()
			print "FAILED"
			return None

	def _generateFile(self, dir, filename, step = 0):
		try:
			hash = self._getHash(dir + filename)
			if hash:
				filesize = os.path.getsize(dir + filename)
				self._print('<File Name="%s" Size="%s" TTH="%s"/>'%(filename.replace("&","&amp;"),filesize.__str__(),hash), step)
		except:
			print sys.exc_info()
			pass
		self._alreadyfiles = self._alreadyfiles + 1
		print "%s..."%(100.0 * (float(self._alreadyfiles)/float(self._countfiles)))

	def _generateDirectoryEnd(self, step = 0):
		self.dirstack.pop()
		self._print("</Directory>",step)

	def _generateHeaders(self):
		self._print('<FileListing Version="1" CID="GVDUN3AFGU3WCZGZP5UY2MN4PMYCPUR6ZBSVF4I" Base="/" Generator="DC++ 0.698">')

	def _generateFinish(self):
		self._print("</FileListing>")

	def print_current(self,prefix,dir,root, virtualdir,step = 0):
		if dir == root:
			self._generateDirectory(virtualdir, step)
		else:
			self._generateDirectory(dir,step)
		listd = ()
		try:
			listd = os.listdir(prefix + '/' +  dir)
		except:
			print sys.exc_info()
			pass
		filelist = []
		dirlist = []
		for i in listd:
			try:
				if os.path.isdir(prefix + '/' + dir + '/' + i):
					dirlist.append(i)
				else:
					filelist.append(i)
			except:
				pass
		for i in dirlist:
			self.print_current(prefix + '/' +  dir, i, root, virtualdir, step + 4)
		for i in filelist:
			self._generateFile(prefix + '/' + dir + '/', i, step)
		self._generateDirectoryEnd(step)
